#include "CSystemSettingsDlg.h"

#include <QFile>
#include <QDateTime>
#include <QProcess>
#include <QTextStream>
#include "custom/CToastBox.h"
#include "CAudioBroadcast.h"

CSystemSettingsDlg::CSystemSettingsDlg(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
    setWindowFlag(Qt::FramelessWindowHint, true);
    setWindowFlag(Qt::Tool, true);

    // get information
    update_system_information();
}

void CSystemSettingsDlg::update_system_information()
{
    // get system volume
#ifdef __arm__
    {
        int vol = 255;
        std::string str;
        FILE *pp = popen("amixer contents | grep -A 3 'numid=10' | grep ': values' | awk -F \",\" '{print $NF}'", "r");
        if (!pp) {
            return;
        }
        char tmp[1024];
        while (fgets(tmp, sizeof(tmp), pp) != NULL)
        {
            str += tmp;
        }

        vol = atoi(str.c_str());
        pclose(pp);

        ui.slider_volume->setValue(vol);
    }
#endif //__arm__

    // get datetime
    ui.edt_datetime->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));

    // get network address
#ifdef __arm__
    {
        std::string str;
        FILE *pp = popen("ifconfig eth0 | grep Mask | awk '{print $2}' | cut -d : -f 2", "r");
        if (!pp) {
            return ;
        }
        char tmp[1024];
        while (fgets(tmp, sizeof(tmp), pp) != NULL)
        {
            str += tmp;
        }
        ui.edt_ip_address->setText(QString::fromStdString(str));
        pclose(pp);
    }
#endif //__arm__
}

void CSystemSettingsDlg::on_btns_modify_datetime_clicked()
{
    // set date time
#ifdef __arm__
    QString dataSys = "date -s \"";
    dataSys += ui.edt_datetime->text().trimmed();
    dataSys += "\"";
    system(dataSys.toUtf8());
    system("hwclock --systohc");
#endif // __arm__
}

void CSystemSettingsDlg::on_btns_modify_volume_clicked()
{
#ifdef __arm__
    int value = ui.slider_volume->value();
    // set system volume
    QString setVol1 = QString("amixer cset numid=13,iface=MIXER,name='Speaker Playback Volume' 127");
    QString setVol2 = QString("amixer cset numid=10,iface=MIXER,name='Playback Volume' %1").arg(value);

    system(setVol1.toLatin1());
    system(setVol2.toLatin1());
    system("alsactl store");
#endif // __arm__
}

void CSystemSettingsDlg::on_btns_modify_network_clicked()
{
    // set network address
#ifdef __arm__
    QString ip = ui.edt_ip_address->text();
    QString gateway_addr = ui.edt_gateway->text();
    if(gateway_addr.isEmpty())
    {
        CToastBox::Info(this,"",tr("网关地址不能为空!"));
        return;
    }
    QString mask_addr = ui.edt_netmask->text();
    if(mask_addr.isEmpty())
    {
        CToastBox::Info(this,"",tr("掩码地址不能为空!"));
        return;
    }
    system("rm /userdata/ip.conf");
    QFile file("/userdata/ip.conf");
    if (!file.open(QIODevice::ReadWrite))
    {
        CToastBox::Info(this, "", tr("Open ip.conf failed"));
        return;
    }
    file.seek(0);
    file.write(ip.toLocal8Bit());
    file.flush();
    file.close();

    QString strAll;
    QStringList strList;
    QFile readFile("/etc/network/interfaces");
    if(!readFile.open((QIODevice::ReadOnly|QIODevice::Text)))
    {
        return;
    }
    QTextStream stream(&readFile);
    strAll = stream.readAll();
    readFile.close();
    QFile writeFile("/etc/network/interfaces");
    if(writeFile.open(QIODevice::WriteOnly|QIODevice::Text))
    {
        QTextStream stream(&writeFile);
        QString tempStr = "auto lo";
        stream << tempStr <<'\n';
        tempStr = "iface lo inet loopback";
        stream << tempStr<<'\n';
        stream <<'\n';
        tempStr = "auto eth0";
        stream << tempStr <<'\n';
        tempStr = "iface eth0 inet static";
        stream << tempStr << '\n';
        tempStr = QString("address %1").arg(ip);
        stream << tempStr << '\n';
        tempStr = QString("netmask %1").arg(mask_addr);
        stream << tempStr << '\n';
        tempStr = QString("gateway %1").arg(gateway_addr);
        stream << tempStr << '\n';
    }
    else
    {
        CToastBox::Error(this, "", tr("IP setting failure!"));
        return;
    }
    writeFile.flush();
    writeFile.close();
    system("sync");
#endif // __arm__
}

void CSystemSettingsDlg::on_btnp_update_clicked()
{
#ifdef __arm__
    QFile dir("/media/usb0/zllocker");
    if(!dir.exists())
    {
        CToastBox::Error(this, "", tr("Can't find update file!"));
        return ;
    }

    int state = system("cp -r /media/usb0/zllocker/* /userdata/shuigongyuan/.; chmod 777 /userdata/shuigongyuan/client;sync;");
    if(-1 == state)
    {
        CToastBox::Error(this, "", tr("Update software failed!"));
    }
    else
    {
        CToastBox::Error(this, "", tr("Update softwate successful,\n please reboot the device!"));
    }
#endif // __arm__
}

void CSystemSettingsDlg::on_btnp_logs_clicked()
{
#ifdef __arm__
    int state = system("cp -r /userdata/shuigongyuan/logs /media/usb0/.");
    if (-1 == state)
    {
        CToastBox::Error(this, "", tr("Copy logs failed"));
    }
    else
    {
        CToastBox::Success(this, "", tr("Copy logs success"));
    }
#endif // __arm__
}
